package com.tm.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONUtilsEx {

	private static ObjectMapper mapper = new ObjectMapper();

	static {

		// 设定JSON转化日期的格式
		mapper.setDateFormat(new SimpleDateFormat(DateUtilsEx.DATE_FORMAT_SEC));

		// TODO 看是否能转话字典表数据,不行的话只能在前台转化
		// mapper.setFilters(filterProvider);
	}

	/**
	 * 对象序列化成JSON字符串
	 * @param obj
	 * @return
	 * @throws ServiceException 
	 */
	public static String serialize(Object obj) {

		StringWriter writer = null;

		try {
			writer = new StringWriter();
			mapper.writeValue(writer, obj);
			writer.close();
		} catch (Exception e) {
			throw new ServiceException("JSON序列化结果异常:" + e.getMessage());
		}

		return writer.toString();
	}

	/**
	 * JSON字符串反序列化成对象
	 * @param jsonStr
	 * @param clazz
	 * @return
	 * @throws ServiceException 
	 */
	public static <T> T deserialize(String jsonStr, Class<T> clazz) throws ServiceException {

		if (!StringUtils.hasText(jsonStr)) {
			return null;
		}

		try {
			return mapper.readValue(jsonStr.replace("\n", ""), clazz);
		} catch (Exception e) {
			throw new ServiceException("JSON反序列化结果异常:" + e.getMessage());
		}
	}
	
	public static String parseRequest2JsonStr(HttpServletRequest request) throws Exception {
        // 读取参数
        InputStream inputStream;
        StringBuffer sb = new StringBuffer();
        inputStream = request.getInputStream();
        String s;
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((s = in.readLine()) != null) {
            sb.append(s);
        }
        in.close();
        inputStream.close();
        String reqStr = sb.toString();

        return reqStr;
    }

}
